import React, { useState, useEffect, useCallback } from 'react';
import { 
    Container, Typography, Snackbar, Alert, ThemeProvider, 
    createTheme, CssBaseline, AppBar, Toolbar, Box, Paper 
} from '@mui/material';
import { blue, orange } from '@mui/material/colors';
import { DataArray as DataIcon } from '@mui/icons-material';
import { configurationApi } from './services/api';
import ConfigurationList from './components/ConfigurationList';
import ConfigurationForm from './components/ConfigurationForm';
import DataPreviewDialog from './components/DataPreviewDialog';

// 创建自定义主题
const theme = createTheme({
    palette: {
        primary: blue,
        secondary: orange,
        background: {
            default: '#f5f5f5'
        }
    },
    components: {
        MuiAppBar: {
            styleOverrides: {
                root: {
                    background: 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
                }
            }
        }
    }
});

function App() {
    // 状态管理
    // 存储所有配置列表
    const [configurations, setConfigurations] = useState([]);
    
    // 新配置的表单数据
    const [currentConfig, setCurrentConfig] = useState({
        configName: '',
        description: '',
        dataCount: 10,
        fields: [{
            fieldName: '',
            fieldType: '',
            minValue: '',
            maxValue: '',
            prefix: '',
            suffix: '',
            format: '',
            fieldOrder: 0
        }]
    });
    
    // 消息提示相关状态
    const [message, setMessage] = useState('');      // 提示消息内容
    const [severity, setSeverity] = useState('success');  // 提示消息类型（success/error）
    const [open, setOpen] = useState(false);         // 提示框显示状态
    
    // 数据预览相关状态
    const [previewData, setPreviewData] = useState([]); // 预览数据
    const [previewOpen, setPreviewOpen] = useState(false); // 预览对话框显示状态
    const [previewConfig, setPreviewConfig] = useState(null); // 保存当前预览的配置

    // 获取配置列表的函数，使用 useCallback 避免不必要的重渲染
    const fetchConfigurations = useCallback(async () => {
        try {
            const response = await configurationApi.getAll();
            setConfigurations(response.data);
        } catch (error) {
            showMessage('获取配置列表失败', 'error');
        }
    }, []);

    // 组件挂载时获取配置列表
    useEffect(() => {
        fetchConfigurations();
    }, [fetchConfigurations]);

    // 处理表单输入变化
    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setCurrentConfig(prev => ({
            ...prev,
            [name]: value
        }));
    };

    // 处理编辑按钮点击
    const handleEdit = (config) => {
        setCurrentConfig(config);
    };

    // 处理表单重置
    const handleReset = () => {
        setCurrentConfig({
            configName: '',
            description: '',
            dataCount: 10,
            fields: [{
                fieldName: '',
                fieldType: '',
                minValue: '',
                maxValue: '',
                prefix: '',
                suffix: '',
                format: '',
                fieldOrder: 0
            }]
        });
    };

    // 修改提交处理函数
    const handleSubmit = async (config) => {
        try {
            if (config.id) {
                // 更新现有配置
                await configurationApi.update(config.id, config);
                showMessage('配置更新成功', 'success');
            } else {
                // 创建新配置
                await configurationApi.create(config);
                showMessage('配置添加成功', 'success');
            }
            // 重置表单
            handleReset();
            // 刷新配置列表
            fetchConfigurations();
        } catch (error) {
            showMessage(config.id ? '配置更新失败' : '配置添加失败', 'error');
        }
    };

    // 处理数据生成
    const handleGenerateData = async (id) => {
        try {
            const config = configurations.find(c => c.id === id);
            const response = await configurationApi.generate(id);
            setPreviewData(response.data);
            setPreviewConfig(config); // 保存当前预览的配置
            setPreviewOpen(true);
            showMessage('数据生成成功', 'success');
        } catch (error) {
            showMessage('数据生成失败', 'error');
        }
    };

    // 处理数据导出为Excel（CSV格式）
    const handleExportData = (format) => {
        if (!previewData || previewData.length === 0) return;

        let content;
        let fileName;
        let mimeType;

        if (format === 'csv') {
            // CSV 格式
            const headers = Object.keys(previewData[0]);
            content = [
                ['序号', ...headers].join(','),
                ...previewData.map((row, index) => 
                    [index + 1, ...Object.values(row)].join(',')
                )
            ].join('\n');
            fileName = 'generated_data.csv';
            mimeType = 'text/csv;charset=utf-8;';
            content = '\uFEFF' + content; // 添加 BOM 以支持中文
        } else {
            // JSON 格式
            content = JSON.stringify(previewData, null, 2);
            fileName = 'generated_data.json';
            mimeType = 'application/json;charset=utf-8;';
        }

        // 创建并下载文件
        const blob = new Blob([content], { type: mimeType });
        const link = document.createElement("a");
        if (link.download !== undefined) {
            const url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", fileName);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    };

    // 处理配置删除
    const handleDelete = async (id) => {
        try {
            await configurationApi.delete(id);
            showMessage('配置删��成功', 'success');
            fetchConfigurations();
        } catch (error) {
            showMessage('配置删除失败', 'error');
        }
    };

    // 显示提示消息
    const showMessage = (msg, sev) => {
        setMessage(msg);
        setSeverity(sev);
        setOpen(true);
    };

    // 渲染界面
    return (
        <ThemeProvider theme={theme}>
            <CssBaseline />
            {/* 顶部导航栏 */}
            <AppBar position="fixed">
                <Toolbar>
                    <DataIcon sx={{ mr: 2 }} />
                    <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
                        数据宝
                    </Typography>
                    <Typography variant="subtitle2">
                        智能数据生成平台
                    </Typography>
                </Toolbar>
            </AppBar>

            {/* 主要内容区域 */}
            <Box sx={{ pt: 10, pb: 4, minHeight: '100vh' }}>
                <Container maxWidth="lg">
                    {/* 欢迎信息 */}
                    <Paper 
                        elevation={3} 
                        sx={{ 
                            p: 3, 
                            mb: 3, 
                            background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
                            color: 'white'
                        }}
                    >
                        <Typography variant="h4" gutterBottom>
                            欢迎使用数据宝
                        </Typography>
                        <Typography variant="subtitle1">
                            快速生成测试数据，提升开发效率
                        </Typography>
                    </Paper>

                    {/* 配置表单 */}
                    <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
                        <Typography variant="h5" gutterBottom color="primary">
                            配置管理
                        </Typography>
                        <ConfigurationForm 
                            config={currentConfig}
                            onInputChange={handleInputChange}
                            onSubmit={handleSubmit}
                            onReset={handleReset}
                        />
                    </Paper>

                    {/* 配置列表 */}
                    <Paper elevation={3} sx={{ p: 3 }}>
                        <Typography variant="h5" gutterBottom color="primary">
                            配置列表
                        </Typography>
                        <ConfigurationList 
                            configurations={configurations}
                            onGenerateData={handleGenerateData}
                            onDelete={handleDelete}
                            onEdit={handleEdit}
                        />
                    </Paper>
                </Container>
            </Box>

            {/* 数据预览对话框 */}
            <DataPreviewDialog 
                open={previewOpen}
                onClose={() => setPreviewOpen(false)}
                data={previewData}
                config={previewConfig}
                onExport={handleExportData}
            />

            {/* 提示消息 */}
            <Snackbar 
                open={open} 
                autoHideDuration={3000} 
                onClose={() => setOpen(false)}
            >
                <Alert severity={severity} onClose={() => setOpen(false)}>
                    {message}
                </Alert>
            </Snackbar>
        </ThemeProvider>
    );
}

export default App; 